package core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigPropertiesHolder {
	private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertiesHolder.class);

	private static ConfigPropertiesHolder _instance = new ConfigPropertiesHolder();

	public static ConfigPropertiesHolder getInstance() {
		return _instance;
	}

	private Properties configProperties;

	private ConfigPropertiesHolder() {
		configProperties = new Properties();
		if(new File("config.properties").exists() == false) {
			createDefaultPropertiesFile();
		}
		FileInputStream in;
		try {
			in = new FileInputStream("config.properties");
			configProperties.load(in);
		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
	}

	public void createDefaultPropertiesFile() {
		PrintWriter printWriter;
		try {
			printWriter = new PrintWriter("config.properties", "UTF-8");
			for (Property property : Property.values()) {
				printWriter.println("# " + property.getDescription());
				printWriter.println(property.getKey() + " = " + property.getDefaultValue());
			}
			printWriter.close();
		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public String getProperty(Property property) {
		if (configProperties.getProperty(property.getKey()) != null) {
			return configProperties.getProperty(property.getKey());
		} else {
			return property.getDefaultValue();
		}
	}
	
	public void setProperty(Property property, String value) {
		configProperties.setProperty(property.getKey(), value);
	}
}
